package com.kabuda.zhugehot200;

/**
 * @author kabuda
 * @date 2025-03-15 21:07
 * @description
 */
public class t441_排列硬币 {
    public static void main(String[] args) {
        System.out.println(arrangeCoins(1804289383));
        System.out.println(arrangeCoins2(1804289383));
    }

    /**
     * 暴力迭代
     *
     * @param n
     * @return
     */
    public static int arrangeCoins(int n) {
        int sum = n;
        for (int i = 1; i < n; i++) {
            sum -= i;
            if (sum <= 0) {
                return i - 1;
            }
        }
        return 0;
    }

    /**
     * 二分查找
     *
     * @param n
     * @return
     */
    public static int arrangeCoins2(int n) {
        int left = 1;
        int right = n;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if ((long) mid * (mid + 1) / 2 <= n && (long) (mid + 1) * (mid + 2) / 2 > n) {
                return mid;
            } else if ((long) mid * (mid + 1) / 2 > n) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return 0;
    }
}
